package com.ebeitech.auction.view.auction;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.ebeitech.auction.R;
import com.ebeitech.auction.bean.Auction;
import com.ebeitech.auction.bean.LandInfo;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.library.ui.CommonItemView;
import com.ebeitech.library.util.DimenUtils;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.WindowsUtil;
import com.tencent.qcloud.tlslibrary.helper.Util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by alice on 2017/11/1.
 */
public class AuctionLandFragment extends Fragment {

	@BindView(R.id.listView)
	ListView mListView;
	@BindView(R.id.view_title)
	View viewTitle;
	com.baidu.mapapi.map.MapView mMapView;
	Unbinder unbinder;

	private Context mContext;
	private BaseAdapter mAdapter;
	private List<String> names = new ArrayList<String>();
	private List<String> values = new ArrayList<String>();
	private List<String> groupNames = new ArrayList<String>();
	private BaiduMap mBaiduMap;

	private Auction mAuction;
	private LandInfo mLandInfo;

	private ImageView ivMapControl,ivMapLocation;
	private RelativeLayout rlMapView;

	private boolean isSmall = true;

	private int statusHeight;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ebei_activity_listview, null);
		unbinder = ButterKnife.bind(this, view);
		mContext = getActivity();
		statusHeight = getStatusBarHeight();
		Intent intent = getActivity().getIntent();
		if (intent != null) {
			mAuction = (Auction) intent.getSerializableExtra(CommonConstants.AUCTION);
		}
		mLandInfo = mAuction.getLandInfo();

		initView();
		initData();
		return view;
	}

	private void initView() {
		viewTitle.setVisibility(View.GONE);
		rlMapView = new RelativeLayout(getActivity());
		AbsListView.LayoutParams params = new AbsListView.LayoutParams(WindowsUtil.getInstance(getActivity()).getWindowX(), ViewGroup.LayoutParams.WRAP_CONTENT);
		params.height = (WindowsUtil.getInstance(getActivity()).getWindowY() - (2 * getResources().getDimensionPixelSize(R.dimen.ebei_title_bar_image_size))-statusHeight)/2;
		rlMapView.setLayoutParams(params);
		mMapView = new MapView(mContext);
		rlMapView.addView(mMapView);
		//放大缩小按键
		ivMapControl = new ImageView(getActivity());
		RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(DimenUtils.dip2px(getActivity(),40),DimenUtils.dip2px(getActivity(),40));
		rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		rlParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		rlParams.rightMargin = DimenUtils.dip2px(mContext,20);
		rlParams.bottomMargin = DimenUtils.dip2px(mContext,20);
		int padding = DimenUtils.dip2px(mContext,10);
		ivMapControl.setPadding(padding,padding,padding,padding);
		ivMapControl.setImageResource(R.drawable.ebei_icon_map_fullscreen);
		ivMapControl.setBackgroundResource(R.drawable.ebei_icon_cur_location_bg);
		rlMapView.addView(ivMapControl,rlParams);

		ivMapLocation = new ImageView(getActivity());
		RelativeLayout.LayoutParams rlLocationParams = new RelativeLayout.LayoutParams(DimenUtils.dip2px(getActivity(),40),DimenUtils.dip2px(getActivity(),40));
		rlLocationParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		rlLocationParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		rlLocationParams.rightMargin = DimenUtils.dip2px(mContext,20);
		rlLocationParams.bottomMargin = DimenUtils.dip2px(mContext,80);
		ivMapLocation.setPadding(padding,padding,padding,padding);
		ivMapLocation.setImageResource(R.drawable.ebei_icon_cur_location);
		ivMapLocation.setBackgroundResource(R.drawable.ebei_icon_cur_location_bg);
		rlMapView.addView(ivMapLocation,rlLocationParams);

		mListView.addHeaderView(rlMapView);
		mListView.setDivider(null);
		mAdapter = new LandInfoAdapter();
		mListView.setAdapter(mAdapter);
		//点击放大缩小
		ivMapControl.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
				params.width  = WindowsUtil.getInstance(getActivity()).getWindowX();
				if (isSmall) {
					params.height = WindowsUtil.getInstance(getActivity()).getWindowY() - (2 * getResources().getDimensionPixelSize(R.dimen.ebei_title_bar_image_size))-statusHeight;
					ivMapControl.setImageResource(R.drawable.ebei_icon_map_cancelfullscreen);
					ivMapControl.setBackgroundResource(R.drawable.ebei_icon_cur_location_bg);
				}
				else {
					params.height = (WindowsUtil.getInstance(getActivity()).getWindowY() - (2 * getResources().getDimensionPixelSize(R.dimen.ebei_title_bar_image_size))-statusHeight)/2;
					ivMapControl.setImageResource(R.drawable.ebei_icon_map_fullscreen);
					ivMapControl.setBackgroundResource(R.drawable.ebei_icon_cur_location_bg);
				}
				rlMapView.setLayoutParams(params);
				isSmall = !isSmall;
			}
		});

		ivMapLocation.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				LatLng latLng;
				if (mLandInfo.getLandArranges()!=null&&mLandInfo.getLandArranges().size()!=0) {
					//存放经纬度 顺序分别为最小经度 最小纬度 最大经度 最大纬度
					List<String> lats = new ArrayList<>();
					List<String> lngs = new ArrayList<>();
					for (int i = 0; i < mLandInfo.getLandArranges().size(); i++)
					{
						if (!mLandInfo.getLandArranges().get(i).contains(":"))
							continue;
						String[] latlngs = mLandInfo.getLandArranges().get(i).split(":");
						lats.add(latlngs[0]);
						lngs.add(latlngs[1]);
					}
					if (lats.size()!=0&&lngs.size()!=0)
					{
						double centerLat = (StringUtil.parseDouble(Collections.max(lats)) + StringUtil.parseDouble(Collections.min(lats)))/2;
						double centerLng = (StringUtil.parseDouble(Collections.max(lngs)) + StringUtil.parseDouble(Collections.min(lngs)))/2;
						latLng = new LatLng(centerLat,centerLng);
					}
					else {
						latLng = null;
					}

				}
				else {
					if ((mLandInfo.getLatitude()==null||"".equals(mLandInfo.getLatitude()))&&
							(mLandInfo.getLongitude()==null||"".equals(mLandInfo.getLongitude())))
						return;
					latLng = new LatLng(StringUtil.parseDouble(mLandInfo.getLatitude()), StringUtil.parseDouble(mLandInfo.getLongitude()));

				}
				if (latLng!=null) {
					MapStatus.Builder builder = new MapStatus.Builder();
					builder.target(latLng);
					if (mLandInfo.getMapRank() != null && !"".equals(mLandInfo.getMapRank())) {
						builder.zoom(Float.valueOf(mLandInfo.getMapRank()));
					} else {
						builder.zoom(15.0f);
					}
					mMapView.getMap().animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
				}
				else {
					Util.showToast(getActivity(),"无法获取到边界");
				}
			}
		});
	}

	private void initMap(){
		// 获取地图控件引用
		mBaiduMap = mMapView.getMap();

		MapStatus.Builder builder = new MapStatus.Builder();
		if (mLandInfo.getMapRank()!=null&&!"".equals(mLandInfo.getMapRank()))
		{
			builder.zoom(Float.valueOf(mLandInfo.getMapRank()));
		}
		else {
			builder.zoom(17);
		}

		MapStatusUpdate mapStatus = MapStatusUpdateFactory.newMapStatus(builder.build());
		if (mBaiduMap != null) {
			mBaiduMap.animateMapStatus(mapStatus);
			mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {

				@Override
				public boolean onMapPoiClick(MapPoi arg0) {
					// TODO Auto-generated method stub
					return false;
				}

				@Override
				public void onMapClick(LatLng arg0) {
					// TODO Auto-generated method stub

				}
			});

			mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {

				@Override
				public void onTouch(MotionEvent motionEvent) {
					if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
						mListView.requestDisallowInterceptTouchEvent(false);
					}else {
						mListView.requestDisallowInterceptTouchEvent(true);
					}
				}
			});
		}

		mMapView.showZoomControls(false);
		// 删除百度地图logo
		mMapView.removeViewAt(1);

		// LatLng是(纬度,经度)
		List<String> landArranges = mLandInfo.getLandArranges();
		LatLng location = null;
		if (landArranges != null && landArranges.size() > 0) {
			List<LatLng> points= getRailPointsList(landArranges);
			if(points.size() > 0 ){
				location = points.get(0);
				// 构建绘制多边形的Option对象
				OverlayOptions polygonOption = new PolygonOptions().points(points).stroke(new Stroke(5, getResources().getColor(R.color.ebei_red))).fillColor(getResources().getColor(R.color.ebei_transparent));
				// 在地图上添加多边形Option，用于显示项目区域
				if (mBaiduMap != null) {
					mBaiduMap.addOverlay(polygonOption);
				}
			}
		}

		String centerPoint = mLandInfo.getLatitude() + ":" + mLandInfo.getLongitude();
//		String centerPoint = "23.147088:113.350943";//"31.507927:120.349538";//Alice Modify
		if (!StringUtil.isEmpty(centerPoint)) {
			if (centerPoint.contains(":") && !centerPoint.contains("null")) {
				try {
					String[] pointer = centerPoint.split(":");
					location = new LatLng(StringUtil.parseDouble(pointer[0]), StringUtil.parseDouble(pointer[1]));
				} catch (NumberFormatException nfe) {
					location = null;
				}
			}
		}
		if(location != null){
			//显示项目地点
			builder = new MapStatus.Builder();
			builder.target(location);
			if (mLandInfo.getMapRank()!=null&&!"".equals(mLandInfo.getMapRank()))
			{
				builder.zoom(Float.valueOf(mLandInfo.getMapRank()));
			}
			else {
				builder.zoom(17);
			}
			mapStatus = MapStatusUpdateFactory.newMapStatus(builder.build());
			if (mBaiduMap != null) {
				mBaiduMap.animateMapStatus(mapStatus);
			}
		}
	}

	private List<LatLng> getRailPointsList(List<String> landArranges){
		List<LatLng> pts = new ArrayList<LatLng>();
		for (String railPoint : landArranges) {
			if (railPoint.contains(":")) {
				String[] pointer = railPoint.split(":");
				LatLng pt = new LatLng(StringUtil.parseDouble(pointer[0]), StringUtil.parseDouble(pointer[1]));
				pts.add(pt);
			}
		}
		return pts;
	}

	private void initData() {
		if (mLandInfo == null) {
			return;
		}

		names.clear();
		values.clear();
		groupNames.clear();

		names.add(getString(R.string.ebei_land_name));
		values.add(mLandInfo.getLandName());
		groupNames.add(getString(R.string.ebei_land_name));

		names.add(getString(R.string.ebei_land_code));
		values.add(mLandInfo.getLandNo());

		names.add(getString(R.string.ebei_land_location));
		values.add(mLandInfo.getLocation());

		names.add(getString(R.string.ebei_follow_area));
		values.add(mLandInfo.getAreaName());
		groupNames.add(getString(R.string.ebei_follow_area));

		names.add(getString(R.string.ebei_develop_area));
		values.add(mLandInfo.getDevelopArea());

		names.add(getString(R.string.ebei_project_type));
		values.add(mLandInfo.getProjectType());

		names.add(getString(R.string.ebei_manage_type));
		values.add(mLandInfo.getManageType());
		groupNames.add(getString(R.string.ebei_manage_type));

		names.add(getString(R.string.ebei_is_first_stage));
		values.add(mLandInfo.getIsFirststage());

		names.add(getString(R.string.ebei_contract_holderate));
		values.add(mLandInfo.getContractHolderate() + "%");

		names.add(getString(R.string.ebei_current_area_properties));
		values.add(mLandInfo.getAreaProperties());
		groupNames.add(getString(R.string.ebei_current_area_properties));

		names.add(getString(R.string.ebei_is_have_gard_house));
		values.add(mLandInfo.getIsHaveGardHouse());

		names.add(getString(R.string.ebei_hold_area_meter));
		values.add(mLandInfo.getHoldArea());

		names.add(getString(R.string.ebei_land_price_total));
		values.add(mLandInfo.getLandPrice());
		groupNames.add(getString(R.string.ebei_land_price_total));

		names.add(getString(R.string.ebei_land_price_per_mu));
		values.add(mLandInfo.getPerMu());

		names.add(getString(R.string.ebei_plot_ratio));
		values.add(mLandInfo.getVrate());

		names.add(getString(R.string.ebei_land_price_plot));
		values.add(mLandInfo.getVfacePrice());
		groupNames.add(getString(R.string.ebei_land_price_plot));

		names.add(getString(R.string.ebei_land_price_start));
		values.add(mLandInfo.getStartPrice());

		names.add(getString(R.string.ebei_land_price_limit));
		values.add(mLandInfo.getLimitPrice());

		names.add(getString(R.string.ebei_land_price_house_sell));
		values.add(mLandInfo.getHousePrice());

		names.add(getString(R.string.ebei_possess_square_meter_start));
		values.add(mLandInfo.getHolderArea());
		groupNames.add(getString(R.string.ebei_possess_square_meter_start));

		names.add(getString(R.string.ebei_public_building_disposition_square_meter));
		values.add(mLandInfo.getSelfHouseArea());

		names.add(getString(R.string.ebei_plot_measure_meter));
		values.add(mLandInfo.getChargeArea());

		mAdapter.notifyDataSetChanged();

		initMap();
	}

	class LandInfoAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return names.size();
		}

		@Override
		public Object getItem(int position) {
			return names.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			CommonItemView commonItemView;
			if (convertView == null) {
				commonItemView = new CommonItemView(mContext);
				commonItemView.setItemStyle(CommonItemView.ItemStyle.DEFAULT);
				convertView = commonItemView;
			} else {
				commonItemView = (CommonItemView) convertView;
			}
			String name = names.get(position);
			commonItemView.setTitle(name);
			commonItemView.setTextValue(values.get(position));

			if (groupNames.contains(name) && position > 0) {
				commonItemView.setIsHeaderViewVisible(true);
			} else {
				commonItemView.setIsHeaderViewVisible(false);
			}

			boolean isDividerVisible = true;
			if (position == names.size() - 1
					|| (position + 1 < names.size() && groupNames.contains(names.get(position + 1)))) {
				isDividerVisible = false;
			}
			commonItemView.setIsDividerViewVisible(isDividerVisible);
			if (position == names.size() - 1) {
				commonItemView.setIsFooterViewVisible(true, true);
			} else {
				commonItemView.setIsFooterViewVisible(!isDividerVisible);
			}

			return convertView;
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mMapView.onDestroy();
		unbinder.unbind();
	}

	public int getStatusBarHeight() {
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0, statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}

}
